# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "不倒翁-中老年骨折保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(50, 91)],
                # 保障期限
                "days": ["1y"],
                # 保障人数
                "people_count": ["1"],
                # 意外伤残身故
                "accident_death": ["10000"],
                # 意外骨折
                "accident_fracture": ["25000"],
                # 骨折住院津贴
                "fracture_allowance": ["50/天"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(50, 91)],
                # 保障期限
                "days": ["1y"],
                # 保障人数
                "people_count": ["1"],
                # 意外伤残身故
                "accident_death": ["20000"],
                # 意外骨折
                "accident_fracture": ["50000"],
                # 骨折住院津贴
                "fracture_allowance": ["100/天"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"],
                             plan[k]["accident_fracture"], plan[k]["fracture_allowance"]):
                data = Helper.formatProductInfo(plan[k], v)
                yield data

    # 执行爬虫
    def requestJson(self):
        for v in self.genProductInfo():
            data = {"ageLimit": {"ageTo": v["year"], "ageFrom": v["year"]}, "dayLimit": {"dayTo": "366", "dayFrom": "366"},
                    "planCode": "TABBIP1(N)" if v["accident_death"] == "10000" else "TABBIP2(N)", "planName": "标准计划" if v["accident_death"] == "10000" else "升级计划", "productCode": "HET-BUDAOWENG",
                    "productName": "不倒翁-中老年骨折保险", "day": "366"}

            payload = json.dumps( data )
            r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
            if r.status_code == 200 and "premium" in r.text:
                price = Helper.decimalParse( r.json()["premium"])
                data = {
                    "name":self.name,
                    "company":"京东安联",
                    "price":price
                }
                print( data )
                data.update( v )
                Helper.mergeTable( self.name,self.mysql,data )
